<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '项目课题变更单' : '新建项目课题变更单'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: isDraft || flowContext.isStartNode,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的项目课题变更申请` }),
      submit: submitAudit,
      finish: () => submitAudit({}),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <template #toolbar-right> </template>
    <FormHolder ref="form" label-width="130px" :disabled="isDisabled" :model="entity">
      <FormItemGroup block-title="基本信息">
        <FormInput :value="entity.createBy" prop="createBy" label="作者" disabled />
        <FormInput :value="entity.deptFullName" prop="deptFullName" label="所属单位" disabled />
        <FormInput :value="entity.projectName" prop="projectName" label="所属项目" disabled>
          <ElLink underline type="primary" @click="$router.push(`/tech-project/project-manage/information/ProjectInformationForm/${entity.projectId}`)">
            {{ entity.projectName }}
          </ElLink>
        </FormInput>
        <FormDatePicker v-model="entity.modifyTime" prop="modifyTime" label="变更时间" :placeholder="null" date-time disabled />
        <FormInput v-model="entity.subject" prop="subject" label="标题" required />
        <FormTextarea v-model="entity.reason" prop="reason" label="变更理由" />
      </FormItemGroup>
      <FormItemGroup enabled :gutter="0" block-title="调整列表">
        <FormTablePlus
          :key="entity.status"
          v-model="entity.topics"
          required
          label="项目课题"
          hide-label
          prefix-pick
          :disabled="isDisabled"
          label-width="0"
          prop="topics"
          :columns="topicColumns"
          @add-row="isTopicEditDialogVisible = true">
          <template #action="{ row }">
            <span :style="{ color: row.action === 2 ? 'red' : row.action === 3 ? 'orange' : 'green' }">
              {{ options[row.action] }}
            </span>
          </template>
          <template #toolbar-left="{ addRow }">
            <ElButton size="mini" class="table-header-button add" icon="el-icon-circle-plus" type="text" @click="addRow">添加</ElButton>
            <ElButton size="mini" class="table-header-button add" icon="el-icon-edit-outline" type="text" @click="adjustTopic">调整</ElButton>
            <ElButton size="mini" class="table-header-button remove" icon="el-icon-remove" type="text" @click="deleteTopic">删除</ElButton>
          </template>
          <template #handle="{ remove }">
            <TableColumn #default="{ row, $index }" label="操作" align="center">
              <ElButton v-if="isDraft && isCreator" size="mini" type="text" @click="addTopic($index)">添加</ElButton>
              <ElButton v-if="isDraft && isCreator && row.action !== 2" size="mini" type="text" @click="editTopic(row, $index)">编辑</ElButton>
              <Confirmable v-if="isDraft && isCreator" tag="ElButton" title="删除" message="您确定要删除该行吗？" size="mini" type="text" @click="remove">
                删除
              </Confirmable>
              <ElButton v-if="!isDraft" size="mini" type="text" @click="viewTopic(row, $index)">查看</ElButton>
            </TableColumn>
          </template>
        </FormTablePlus>
      </FormItemGroup>
    </FormHolder>
    <TopicEditDialog
      v-if="isTopicEditDialogVisible"
      :value="topic"
      :disabled="isView"
      :visible.sync="isTopicEditDialogVisible"
      @close="topic = null"
      @confirm="onTopicConfirm" />
    <ProjectTopicsDialog
      v-if="isProjectTopicsDialogVisible"
      :title="dialogTitle"
      :project-id="projectId || entity.projectId"
      :disabled-row-keys="entity.topics.map(value => value.originalId).filter(value => value)"
      :multiple="multiple"
      :visible.sync="isProjectTopicsDialogVisible"
      @confirm="onSelectRow" />
  </FormView>
</template>

<script>
  import { create, load, save, update } from './api'
  import flowForm from '@/vue/mixin/flow-form'
  import { topicColumns } from '@/module/tech-project/project-manage'
  import TopicEditDialog from '@/module/tech-project/project-manage/topic/TopicEditDialog.vue'
  import ProjectTopicsDialog from '@/module/tech-project/project-manage/topic/ProjectTopicsDialog.vue'

  export default {
    name: 'ProjectTopicUpdateForm',
    components: { ProjectTopicsDialog, TopicEditDialog },
    docType: 'WF_PROJECT_TOPIC',
    relativeViewId: 'ProjectTopicUpdateView',
    mixins: [flowForm],
    props: {
      projectId: String
    },
    data() {
      return {
        isView: false,
        isTopicEditDialogVisible: false,
        isProjectTopicsDialogVisible: false,
        options: { 2: '删除', 1: '添加', 3: '调整' },
        topicColumns: [
          ...topicColumns,
          {
            label: '动作',
            prop: 'action',
            align: 'center'
          }
        ],
        dialogTitle: '',
        multiple: false,
        editIndex: null,
        topic: null,
        entity: {
          id: null,
          unid: null,
          createTime: null,
          createBy: null,
          createId: null,
          deptId: null,
          deptFullName: null,
          updateTime: null,
          updateId: null,
          updateBy: null,
          tenantId: null,
          delFlag: null,
          modifyTime: null,
          subject: null,
          reason: null,
          projectId: null,
          projectName: null,
          status: null,
          topics: []
        }
      }
    },
    methods: {
      create() {
        return create({ projectId: this.projectId })
      },
      load,
      save,
      update,
      async initEntity(id) {
        const entity = await this.loadEntity(id)
        entity.topics = entity.topics || []
        this.entity = entity
      },
      deleteTopic() {
        this.multiple = true
        this.dialogTitle = '请选择要删除的课题'
        this.isProjectTopicsDialogVisible = true
      },
      adjustTopic() {
        this.multiple = false
        this.dialogTitle = '请选择要调整的课题'
        this.isProjectTopicsDialogVisible = true
      },
      async onSelectRow(rows) {
        if (this.multiple) {
          // 删除
          this.entity.topics.push(
            ...rows.map(value => {
              value.action = 2
              value.rootId = value.rootId || value.id
              value.originalId = value.id
              value.id = null
              return value
            })
          )
        } else {
          // 调整
          rows.action = 3
          rows.rootId = rows.rootId || rows.id
          rows.originalId = rows.id
          rows.id = null
          this.topic = rows
          await this.$nextTick()
          this.isTopicEditDialogVisible = true
        }
      },
      addTopic(index) {
        this.editIndex = index
        this.isTopicEditDialogVisible = true
      },
      viewTopic(row, index) {
        this.topic = row
        this.isView = true
        this.isTopicEditDialogVisible = true
      },
      editTopic(row, index) {
        this.editIndex = index
        this.topic = row
        this.isTopicEditDialogVisible = true
      },
      onTopicConfirm(topic) {
        if (this.editIndex !== null && this.topic) {
          // 编辑
          this.$set(this.entity.topics, this.editIndex, topic)
          this.editIndex = null
          this.topic = null
        } else if (this.editIndex !== null) {
          // 操作添加
          topic.action = topic.action || 1
          this.entity.topics.splice(this.editIndex + 1, 0, topic)
        } else {
          // 顶部添加
          topic.action = topic.action || 1
          this.entity.topics.push(topic)
        }
      }
    }
  }
</script>
